package com.qf.java2107.yb.hotel.controller.user;

import com.alibaba.druid.util.StringUtils;
import com.qf.java2107.yb.hotel.common.ResultVO;
import com.qf.java2107.yb.hotel.constant.MethodConstant;
import com.qf.java2107.yb.hotel.controller.BaseServlet;
import com.qf.java2107.yb.hotel.entity.BeanFactory;
import com.qf.java2107.yb.hotel.pojo.User;
import com.qf.java2107.yb.hotel.service.UserService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author yb
 * @version 1.0
 * @date 2021-10-27
 **/
@WebServlet("/user")
public class UserController extends BaseServlet {

    private UserService userService = (UserService) BeanFactory.getBean("userService");

    public String login(HttpServletRequest request, HttpServletResponse response) throws Exception{

        String checkCode = request.getParameter("checkCode");

        //验证码
        if(StringUtils.isEmpty(checkCode)) {
            return "<script>alert('验证码不能为空');location.href='" + request.getContextPath() +"/login.jsp'</script>";
        }

        HttpSession session = request.getSession();

        if(!checkCode.equalsIgnoreCase((String) session.getAttribute("sessionCode"))) {
            return "<script>alert('验证码错误');location.href='" + request.getContextPath() + "/login.jsp'</script>";
        }

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        ResultVO vo = userService.login(username, password);

        if(vo.getSuccess()) {
           // System.out.println("-----------------------");
            User user = (User) vo.getData();
            session.setAttribute("loginUser", user);
            if(user.getIsAdmin().intValue() == 1) {
                //去后台
                return MethodConstant.REDIRECT_PREFIX + request.getContextPath() + "/backend/index.jsp";
            }
            //去前台
            return MethodConstant.REDIRECT_PREFIX + request.getContextPath() + "/front/index.jsp";
        }

        return (String) vo.getData();

    }


}
